package com.thirteenClassicsServer.service.impl;

import com.thirteenClassics.dto.BookIdAndCatalogDTO;
import com.thirteenClassics.dto.InsertSentenceJdbDTO;
import com.thirteenClassics.dto.XmlParseDTO;
import com.thirteenClassics.entity.CatalogBook;
import com.thirteenClassics.entity.Sentence;
import com.thirteenClassicsServer.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class XmlParseService {

    @Resource
    private CatalogBookMapper catalogBookMapper;

    @Resource
    private CatalogMapper catalogMapper;

    @Resource
    private XmlPathMapper XmlPathMapper;

    @Resource
    private SentenceMapper sentenceMapper;

    @Resource
    private BookMapper bookMapper;

    private Document document = null;

    private static final Map<String, String> bookTableMap = new HashMap<>();

    static {
        bookTableMap.put("论语", "sentences_lunyu");
        bookTableMap.put("春秋", "sentences_chunqiu");
        bookTableMap.put("春秋公羊传", "sentences_chunqiugongyangzhuan");
        bookTableMap.put("春秋谷梁传", "sentences_chunqiuguliangzhuan");
        bookTableMap.put("春秋榖梁传", "sentences_chunqiuguliangzhuan");
        bookTableMap.put("春秋左传", "sentences_chunqiuzuozhuan");
        bookTableMap.put("尔雅", "sentences_erya");
        bookTableMap.put("礼记", "sentences_liji");
        bookTableMap.put("毛诗", "sentences_maoshi");
        bookTableMap.put("诗经", "sentences_maoshi");
        bookTableMap.put("孟子", "sentences_mengzi");
        bookTableMap.put("尚书", "sentences_shangshu");
        bookTableMap.put("孝经", "sentences_xiaojing");
        bookTableMap.put("仪礼", "sentences_yili");
        bookTableMap.put("周礼", "sentences_zhouli");
        bookTableMap.put("周易", "sentences_zhouyi");
        bookTableMap.put("四书", "sentences_sishu");
    }

    public static String toGetTableName(String bookName) {
        return bookTableMap.getOrDefault(bookName, "sentences");
    }

    public String xmlPath(String bookName) {
        return XmlPathMapper.selectXmlPath(bookName);
    }

    @Transactional
    public void parse(XmlParseDTO xmlParseDTO) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(xmlParseDTO.getPath());
        NodeList juanmingList = document.getElementsByTagName("volume");

        for (int i = 0; i < juanmingList.getLength(); i++) {
            Element juanmingElement = (Element) juanmingList.item(i);
            String juanmingText = juanmingElement.getTextContent();
            juanmingText = juanmingText.replace('，', ',');
            juanmingText = juanmingText + ',';
            System.out.println("volume: " + juanmingText);

            // 查询卷名对应的目录ID
            Long catalogId = catalogMapper.selectCatalogIdByBookName(juanmingText);

            // 设置卷名和目录ID
            BookIdAndCatalogDTO bookIdAndCatalogDTO = new BookIdAndCatalogDTO();
            bookIdAndCatalogDTO.setBookId(xmlParseDTO.getBookId());
            bookIdAndCatalogDTO.setCatalogId(catalogId);

            // 查询卷名对应的入口ID
            Long entryId = catalogBookMapper.selectEntryIdByBookIdAndCatalogId(bookIdAndCatalogDTO);

            // 初始化段落内容
            String jdContent = "";

            // 获取下一个兄弟节点
            Node nextSibling = juanmingElement.getNextSibling();

            // 遍历段落节点
            int p = 0;
            int s = 0;
            while (nextSibling != null) {
                // 判断当前节点是否为段落节点
                if (nextSibling.getNodeName().equals("volume")) {
                    break;
                }
                if (nextSibling.getNodeName().equals("paragraph")) {
                    p++;
                    log.info("-----段落-----");

                    // 将下一个兄弟节点转换为元素节点
                    Element paragraphElement = (Element) nextSibling;

                    // 获取段落下的每个句子
                    NodeList sList = paragraphElement.getElementsByTagName("s");
                    for (int k = 0; k < sList.getLength(); k++) {
                        Element sElement = (Element) sList.item(k);
                        String sText = sElement.getTextContent();
                        sText = cleanString(sText);

                        jdContent = jdContent + sText + "\n";

                        s++;

                        // 插入句子数据
                        InsertSentenceJdbDTO insertSentenceJdbDTO = new InsertSentenceJdbDTO();
                        insertSentenceJdbDTO.setSentence(sText);
                        insertSentenceJdbDTO.setSentenceIds((long) s);
                        insertSentenceJdbDTO.setEntryId(entryId);
                        insertSentenceJdbDTO.setParagraphIds((long) p);

                        Sentence sentence = new Sentence();
                        BeanUtils.copyProperties(insertSentenceJdbDTO, sentence);
                        sentenceMapper.insertJdbSentence(sentence);

                        System.out.println("s: " + sText);
                    }
                    jdContent = jdContent + "\n";
                }
                // 获取下一个兄弟节点
                nextSibling = nextSibling.getNextSibling();
            }
            // 更新段落内容
            CatalogBook catalogBook = new CatalogBook();
            catalogBook.setId(entryId);
            catalogBook.setJdContent(jdContent);
            catalogBookMapper.updatajdContent(catalogBook);
        }
        bookMapper.updateFlag(xmlParseDTO.getBookId());
    }

    public String cleanString(String s) {
        return s.trim().replaceAll("\\r\\n|\\r|\\n", "");
    }


}
